package com.dataex.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.List;

public class OralceDataExSupportImpl implements IDataExSupport {
	Connection conn = null;

	private int pageSize;

	public OralceDataExSupportImpl(Connection conn, String dbType, int pageSize) {
		this.pageSize = pageSize;
		this.conn = conn;
	}

	@Override
	public HashMap<String, Object> getDatas(String columns, String sql, int pageNo) {
		HashMap<String, Object> rowData = new HashMap<String, Object>();
		int endIndex = pageNo * pageSize;
		int startIndex = (pageNo - 1) * pageSize + 1;
		java.sql.PreparedStatement preparedStatement = null;
		try {
			StringBuffer paginationSQL = new StringBuffer(" SELECT " + columns + " FROM ( ");
			paginationSQL.append(" SELECT t.* ,ROWNUM num FROM ( ");
			paginationSQL.append(sql);
			paginationSQL.append("  ) t where ROWNUM <= " + endIndex);
			paginationSQL.append(" ) WHERE  num >= " + startIndex);
			preparedStatement = conn.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			ResultSetMetaData md = resultSet.getMetaData();
			int columnCount = md.getColumnCount();
			while (resultSet.next()) {
				for (int i = 0; i < columnCount; i++) {
					rowData.put(md.getColumnName(i), resultSet.getObject(i));
				}
			}
			return rowData;
		} catch (Exception e) {
		}

		return null;
	}

	@Override
	public int insert(String targetTable, List columns, HashMap<String, Object> datas) {
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("insert into " + targetTable + " (" + columns + ")");
		sqlBuffer.append(" values (");
		for (int i = 0; i < columns.size(); i++) {
			sqlBuffer.append(datas.get(columns.get(i) + ","));
		}
		sqlBuffer.toString().substring(0, sqlBuffer.length() - 1);
		sqlBuffer.append(")");
		java.sql.PreparedStatement ps = null;
		try {
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sqlBuffer.toString());
			for (int i = 1; i < 65536; i++) {
				ps.addBatch();
				// 1w条记录插入一次
				if (i % 10000 == 0) {
					ps.executeBatch();
					conn.commit();
				}
			}
			// 最后插入不足1w条的数据
			ps.executeBatch();
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			return 1;
		}
		return 0;

	}

}
